#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTcpSocket>
#include <QByteArray>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("Tcp服务器");

    //1.创建一个QTcp服务器
    tcpServer = new QTcpServer(this);


    //2.监听后可能立马有数据发过来，但是没有处理函数，所以只能丢弃，
    //应该在监听之前先绑定处理函数
    connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::handleConnection);

    //3.监听
    bool ret = tcpServer->listen(QHostAddress::Any,9090);
    if(ret == false)
    {
        QMessageBox::critical(this,"服务器启动失败",tcpServer->errorString());
        exit(1);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleConnection()
{
    //1.通过tcpServer，得到一个套接字，
    QTcpSocket* socket = tcpServer->nextPendingConnection();
    QString log = "[" + socket->peerAddress().toString() +":"+ QString::number(socket->peerPort())+
            "] 此客户端上线！";
    ui->listWidget->addItem(log);

    //2.套接字要处理请求，也是信号槽的方式
    connect(socket,&QTcpSocket::readyRead,this,[=](){
        //从套接字中读取数据
        QString request = socket->readAll();

        //处理请求
        QString response = process(request);

        //将响应写入套接字
        socket->write(response.toUtf8());

        //记录日志
        QString log = "[" + socket->peerAddress().toString() + ":" + QString::number(socket->peerPort())
                +"] " + " : req->" + request + " response->" + response;
        ui->listWidget->addItem(log);
    });

    //3.关闭连接
    connect(socket,&QTcpSocket::disconnected,this,[=](){
        //记录日志
        QString log = "[" + socket->peerAddress().toString() + ":" + QString::number(socket->peerPort())
                +"] 关闭连接！";
        ui->listWidget->addItem(log);

        //释放套接字资源
        //直接释放，并不是最好的解决方法，Qt采用延后释放，当前释放是在槽函数中，而如果是下一次信号被触发，则上一次的套接字一定
        //使用完毕了，套接字可以安全释放了
        //delete socket;
        socket->deleteLater();

    });
}

QString MainWindow::process(QString & request)
{
    return request;
}

